<template>
  <div class="post-detail-page">
    <div class="content-wrapper">
      <!-- 帖子内容 -->
      <el-card class="post-card" v-loading="loading">
        <template v-if="post">
          <div class="post-header">
            <h1>{{ post.title }}</h1>
            <div class="post-meta">
              <div class="author-info">
                <el-avatar :src="post.avatar" :size="40">{{ post.username?.charAt(0) }}</el-avatar>
                <div class="author-meta">
                  <span class="username">{{ post.username }}</span>
                  <span class="time">{{ formatDate(post.createTime) }}</span>
                </div>
              </div>
              <div class="post-actions" v-if="post.isAuthor || userStore.isAdmin">
                <el-button type="danger" link @click="handleDelete">删除</el-button>
              </div>
            </div>
          </div>

          <div class="post-content">
            <p>{{ post.content }}</p>
          </div>

          <div class="post-footer">
            <div class="stats">
              <span class="views">
                <el-icon><View /></el-icon>
                {{ post.viewCount }}
              </span>
              <span class="comments">
                <el-icon><ChatLineRound /></el-icon>
                {{ post.commentCount }}
              </span>
            </div>
          </div>
        </template>
      </el-card>

      <!-- 评论区 -->
      <div class="comments-section">
        <h2>评论 ({{ post?.commentCount || 0 }})</h2>
        
        <!-- 发表评论 -->
        <el-card class="comment-form" v-if="userStore.isLoggedIn">
          <el-input
            v-model="newComment"
            type="textarea"
            :rows="3"
            placeholder="写下你的评论..."
          />
          <div class="form-footer">
            <el-button type="primary" @click="handleComment" :loading="commenting">
              发表评论
            </el-button>
          </div>
        </el-card>
        <el-card v-else class="login-tip">
          <el-link type="primary" @click="$router.push('/login')">登录</el-link>
          后参与评论
        </el-card>

        <!-- 评论列表 -->
        <div class="comment-list" v-loading="loadingComments">
          <el-card v-for="comment in comments" :key="comment.id" class="comment-card">
            <div class="comment-header">
              <div class="author-info">
                <el-avatar :src="comment.avatar" :size="32">
                  {{ comment.username?.charAt(0) }}
                </el-avatar>
                <div class="author-meta">
                  <span class="username">{{ comment.username }}</span>
                  <span class="time">{{ formatDate(comment.createTime) }}</span>
                </div>
              </div>
              <div class="comment-actions" v-if="comment.isAuthor || userStore.isAdmin">
                <el-button type="danger" link @click="handleDeleteComment(comment)">
                  删除
                </el-button>
              </div>
            </div>

            <div class="comment-content">
              <p>{{ comment.content }}</p>
            </div>

            <!-- 子评论 -->
            <div v-if="comment.children && comment.children.length > 0" class="replies">
              <div v-for="reply in comment.children" :key="reply.id" class="reply-item">
                <div class="reply-header">
                  <div class="author-info">
                    <el-avatar :src="reply.avatar" :size="24">
                      {{ reply.username?.charAt(0) }}
                    </el-avatar>
                    <div class="author-meta">
                      <span class="username">{{ reply.username }}</span>
                      <span class="time">{{ formatDate(reply.createTime) }}</span>
                    </div>
                  </div>
                  <div class="reply-actions" v-if="reply.isAuthor || userStore.isAdmin">
                    <el-button type="danger" link @click="handleDeleteComment(reply)">
                      删除
                    </el-button>
                  </div>
                </div>
                <div class="reply-content">
                  <p>{{ reply.content }}</p>
                </div>
              </div>
            </div>

            <!-- 回复框 -->
            <div class="reply-form" v-if="userStore.isLoggedIn">
              <el-input
                v-model="comment.replyContent"
                placeholder="回复评论..."
                @keyup.enter="handleReply(comment)"
              >
                <template #append>
                  <el-button @click="handleReply(comment)">回复</el-button>
                </template>
              </el-input>
            </div>
          </el-card>
        </div>

        <!-- 评论分页 -->
        <div class="pagination-container" v-if="total > 0">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :total="total"
            :page-sizes="[10, 20, 50]"
            layout="total, sizes, prev, pager, next"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { View, ChatLineRound } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/utils/request'

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()

const loading = ref(false)
const loadingComments = ref(false)
const commenting = ref(false)
const post = ref(null)
const comments = ref([])
const newComment = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

const formatDate = (dateStr) => {
  if (!dateStr) return ''
  return new Date(dateStr).toLocaleString()
}

// 加载帖子详情
const loadPost = async () => {
  loading.value = true
  try {
    const res = await request.get(`/api/forum/posts/${route.params.id}`)
    if (res.code === 200) {
      post.value = res.data
    }
  } catch (error) {
    console.error('加载帖子详情失败:', error)
    ElMessage.error('加载帖子详情失败')
  } finally {
    loading.value = false
  }
}

// 加载评论列表
const loadComments = async () => {
  loadingComments.value = true
  try {
    const res = await request.get(`/api/forum/posts/${route.params.id}/comments`, {
      params: {
        page: currentPage.value,
        size: pageSize.value
      }
    })
    if (res.code === 200) {
      comments.value = res.data.records
      total.value = res.data.total
    }
  } catch (error) {
    console.error('加载评论失败:', error)
    ElMessage.error('加载评论失败')
  } finally {
    loadingComments.value = false
  }
}

// 发表评论
const handleComment = async () => {
  if (!newComment.value.trim()) {
    ElMessage.warning('请输入评论内容')
    return
  }

  commenting.value = true
  try {
    const res = await request.post('/api/forum/comments', {
      postId: route.params.id,
      content: newComment.value
    })
    if (res.code === 200) {
      ElMessage.success('评论成功')
      newComment.value = ''
      loadComments()
      // 刷新帖子信息以更新评论数
      loadPost()
    }
  } catch (error) {
    console.error('发表评论失败:', error)
    ElMessage.error(error.response?.data?.message || '发表评论失败')
  } finally {
    commenting.value = false
  }
}

// 删除评论
const handleDeleteComment = async (comment) => {
  try {
    await ElMessageBox.confirm('确定要删除这条评论吗？', '提示', {
      type: 'warning'
    })
    const res = await request.delete(`/api/forum/comments/${comment.id}`)
    if (res.code === 200) {
      ElMessage.success('删除成功')
      loadComments()
      // 刷新帖子信息以更新评论数
      loadPost()
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除评论失败:', error)
      ElMessage.error(error.response?.data?.message || '删除失败')
    }
  }
}

// 回复评论
const handleReply = async (comment) => {
  if (!comment.replyContent?.trim()) {
    ElMessage.warning('请输入回复内容')
    return
  }

  try {
    const res = await request.post('/api/forum/comments', {
      postId: route.params.id,
      parentId: comment.id,
      content: comment.replyContent
    })
    if (res.code === 200) {
      ElMessage.success('回复成功')
      comment.replyContent = ''
      loadComments()
      // 刷新帖子信息以更新评论数
      loadPost()
    }
  } catch (error) {
    console.error('回复评论失败:', error)
    ElMessage.error(error.response?.data?.message || '回复失败')
  }
}

// 删除帖子
const handleDelete = async () => {
  try {
    await ElMessageBox.confirm('确定要删除这个帖子吗？', '提示', {
      type: 'warning'
    })
    const res = await request.delete(`/api/forum/posts/${route.params.id}`)
    if (res.code === 200) {
      ElMessage.success('删除成功')
      router.push('/front/forum')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除帖子失败:', error)
      ElMessage.error(error.response?.data?.message || '删除失败')
    }
  }
}

const handleSizeChange = (val) => {
  pageSize.value = val
  loadComments()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  loadComments()
}

onMounted(() => {
  loadPost()
  loadComments()
})
</script>

<style lang="scss" scoped>
.post-detail-page {
  .content-wrapper {
    max-width: 1200px;
    margin: 0 auto;
    padding: 20px;
  }

  .post-card {
    margin-bottom: 30px;

    .post-header {
      h1 {
        margin: 0 0 20px;
        font-size: 24px;
        color: #303133;
      }

      .post-meta {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20px;

        .author-info {
          display: flex;
          align-items: center;
          gap: 12px;

          .author-meta {
            display: flex;
            flex-direction: column;

            .username {
              font-weight: bold;
              color: #303133;
            }

            .time {
              font-size: 12px;
              color: #909399;
            }
          }
        }
      }
    }

    .post-content {
      p {
        margin: 0;
        color: #606266;
        line-height: 1.8;
        font-size: 16px;
      }
    }

    .post-footer {
      margin-top: 20px;
      display: flex;
      justify-content: space-between;
      align-items: center;

      .stats {
        display: flex;
        gap: 20px;
        color: #909399;
        font-size: 14px;

        span {
          display: flex;
          align-items: center;
          gap: 4px;
        }
      }
    }
  }

  .comments-section {
    h2 {
      margin: 0 0 20px;
      font-size: 20px;
      color: #303133;
    }

    .comment-form {
      margin-bottom: 30px;

      .form-footer {
        margin-top: 15px;
        text-align: right;
      }
    }

    .login-tip {
      margin-bottom: 30px;
      text-align: center;
      color: #909399;
    }

    .comment-card {
      margin-bottom: 20px;

      .comment-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 12px;

        .author-info {
          display: flex;
          align-items: center;
          gap: 8px;

          .author-meta {
            display: flex;
            flex-direction: column;

            .username {
              font-weight: bold;
              color: #303133;
            }

            .time {
              font-size: 12px;
              color: #909399;
            }
          }
        }
      }

      .comment-content {
        p {
          margin: 0;
          color: #606266;
          line-height: 1.6;
        }
      }

      .replies {
        margin: 15px 0;
        padding-left: 40px;

        .reply-item {
          margin-bottom: 15px;
          padding-bottom: 15px;
          border-bottom: 1px solid #ebeef5;

          &:last-child {
            margin-bottom: 0;
            padding-bottom: 0;
            border-bottom: none;
          }

          .reply-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 8px;

            .author-info {
              display: flex;
              align-items: center;
              gap: 8px;

              .author-meta {
                display: flex;
                flex-direction: column;

                .username {
                  font-weight: bold;
                  color: #303133;
                }

                .time {
                  font-size: 12px;
                  color: #909399;
                }
              }
            }
          }

          .reply-content {
            p {
              margin: 0;
              color: #606266;
              line-height: 1.6;
            }
          }
        }
      }

      .reply-form {
        margin-top: 15px;
      }
    }
  }

  .pagination-container {
    margin-top: 30px;
    display: flex;
    justify-content: center;
  }
}
</style> 